package com.yzm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzm.pojo.*;
import com.yzm.service.AccountService;
import com.yzm.service.HouseholdService;
import com.yzm.service.OperatorService;
import com.yzm.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/operator")
public class OperatorController {
    @Autowired
    private OperatorService operatorService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private HouseholdService householdService;

    @PostMapping("/login")
    public R<Operator> login(HttpServletRequest request,
                             @RequestBody Operator operator) {
        String password = operator.getPassword();
        password = MD5.encrypt(password);
        Operator resultOperator = operatorService.login(operator.getUsername(), password);
        if (resultOperator != null && resultOperator.getStatus() == 1) {
            request.getSession().setAttribute("operator", operator);
            return R.success(resultOperator);
        } else if (resultOperator != null && resultOperator.getStatus() == 0) {
            return R.error("此操作员被禁用!");
        } else {
            return R.error("用户名或密码错误!");
        }
    }

    /**
     * 查询户头以及家庭成员
     *
     * @param page     当前页
     * @param pageSize 页码
     * @param name     姓名
     * @return page
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam("page") int page,
                        @RequestParam("pageSize") int pageSize,
                        @RequestParam(value = "name", required = false) String name) {
        Page<Account> accountPage = new Page<>(page, pageSize);
        Page<ResultAccount> resultAccountPage = new Page<>();
        LambdaQueryWrapper<Account> accountQueryWrapper = new LambdaQueryWrapper<>();
        accountQueryWrapper.like(Strings.isNotEmpty(name), Account::getAccountName, name);
        accountService.page(accountPage, accountQueryWrapper);
        BeanUtils.copyProperties(accountPage, resultAccountPage, "records");
        List<Account> records = accountPage.getRecords();
        List<ResultAccount> resultAccounts = records.stream().map((item) -> {
            ResultAccount resultAccount = new ResultAccount();
            BeanUtils.copyProperties(item, resultAccount);
            Integer accountId = item.getId();
            List<Household> households = householdService.getHouseholdById(accountId);
            if (households != null) {
                resultAccount.setHouseholds(households);
            }
            return resultAccount;
        }).collect(Collectors.toList());
        resultAccountPage.setRecords(resultAccounts);
        System.out.println(resultAccountPage.getRecords().toString());
        return R.success(resultAccountPage);
    }

    /**
     * 获取家庭成员
     *
     * @param accountId 户头id
     * @return
     */
    @GetMapping("/getAllHouseholdsById")
    public R getAllHouseholdsById(@RequestParam Integer accountId) {
        List<Household> households = householdService.getHouseholdById(accountId);
        return R.success(households);
    }

    @GetMapping("/getAllHouseholds")
    public R getAllHouseholds() {
        List<Household> households = householdService.list();
        return R.success(households);
    }

    @GetMapping("/getAllOperators")
    public R<Page> getAllOperators(@RequestParam("page") Integer page,
                                   @RequestParam("pageSize") Integer pageSize,
                                   @RequestParam(value = "username", required = false) String username) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Operator> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Strings.isNotEmpty(username), Operator::getUsername, username);
        operatorService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改户头
     *
     * @param account
     * @return
     */
    @PutMapping("/updateAccount")
    public R update(@RequestBody Account account) {
        try {
            accountService.updateById(account);
            return R.success("修改成功");
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }

    @PutMapping("/updateOperator")
    public R updateOperator(@RequestBody Operator operator) {
        try {
            operatorService.updateById(operator);
            return R.success("修改成功");
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }

    @PutMapping("/updateHousehold")
    public R updateHousehold(@RequestBody Household household) {
        try {
            householdService.updateById(household);
            return R.success("修改成功");
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }


    @GetMapping("/queryOperatorById/{id}")
    public R<Operator> queryOperatorById(@PathVariable Integer id) {
        return R.success(operatorService.getById(id));
    }

    @GetMapping("/queryHouseholdById/{id}")
    public R<Household> queryHouseholdById(@PathVariable Integer id) {
        return R.success(householdService.getById(id));
    }

    @PutMapping("/addOperator")
    public R addOperator(@RequestBody Operator operator) {
        String password = operator.getPassword();
        password = MD5.encrypt(password);
        operator.setPassword(password);
        operatorService.save(operator);
        return R.success("新增成功");
    }

    @PutMapping("/addHousehold")
    public R addOperator(@RequestBody Household household) {
        householdService.save(household);
        return R.success("新增成功");
    }
}
